package com.infinit.selfhelp.common.net.converter
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import android.net.Uri
import java.io.IOException
class UriTypeAdapter : TypeAdapter<Uri>() {
    @Throws(IOException::class)
    override fun write(out: JsonWriter, value: Uri?) {
        if (value == null) {
            out.nullValue()
        } else {
            out.value(value.toString())
        }
    }

    @Throws(IOException::class)
    override fun read(input: JsonReader): Uri? {
        return when (input.peek()) {
            com.google.gson.stream.JsonToken.NULL -> {
                input.nextNull()
                null
            }
            com.google.gson.stream.JsonToken.BEGIN_OBJECT -> {
                input.beginObject()
                var uriString: String? = null
                while (input.hasNext()) {
                    when (input.nextName()) {
                        "uri" -> uriString = input.nextString()
                        else -> input.skipValue()
                    }
                }
                input.endObject()
                uriString?.let { Uri.parse(it) }
            }
            else -> Uri.parse(input.nextString())
        }
    }
}